package com.example.hidesms.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.text.Spannable;
import android.text.Spannable.Factory;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Transformation;
import android.widget.LinearLayout;

import com.example.hidesms.R;
import com.example.hidesms.bo.SmsBO;
import com.example.hidesms.dto.CallInfo;
import com.example.hidesms.dto.CoolSmsItem;
import com.example.hidesms.dto.CoolTitleItem;
import com.example.hidesms.dto.SMSItem;
import com.example.hidesms.sqlite.DataBaseHelper;

public class Utils {
	public static final int	IO_BUFFER_SIZE	= 8 * 1024;

	public static Drawable loadImageFromUrl(String imageUrl) {
		return null;
	}

	public static ArrayList<SMSItem> getAllSms(Context context) {
		ArrayList<SMSItem> lstSms = new ArrayList<SMSItem>();
		SMSItem objSms = new SMSItem();
		Uri message = Uri.parse("content://sms/");
		ContentResolver cr = context.getContentResolver();
		Cursor c = cr.query(message, null, null, null, null);
		// context.startManagingCursor(c);
		int totalSMS = c.getCount();

		if (c.moveToFirst()) {
			for (int i = 0; i < totalSMS; i++) {

				objSms = new SMSItem();
				objSms.setId(c.getInt(c.getColumnIndexOrThrow("_id")));
				String address = c.getString(c.getColumnIndexOrThrow("address"));
				String[] contactData = getContactByNumber(address, context);
				Uri photoUri = null;
//				Log.e("contactData", "contactData " + contactData);
				if (contactData != null) {
					// displayName = contactData[0];
					objSms.setAddressNameS(contactData[0]);
					if (contactData[1] != null)
						photoUri = Uri.parse(contactData[1]);
				}else{
					objSms.setAddressNameS(address);
				}
				if (photoUri!=null) {
					InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context
							.getContentResolver(), photoUri);
					
					Bitmap bm = BitmapFactory.decodeStream(input);
					if (bm != null) {
						ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
						if (bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)) {
							objSms.setImage(byteArrayOutputStream.toByteArray());
//							Log.e("bitmap", " bitmap "+byteArrayOutputStream.toByteArray());
//							Log.e("bitmap", " contactData "+contactData[0]);
						}
					}
				}
//				if (photoUri != null) {
//					Log.e("getAllSms", "photo " + getRealPathFromURI(photoUri, cr));
//				}
				objSms.setAddress(address);
				objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
				objSms.setReadState(c.getString(c.getColumnIndex("read")));
				objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
				objSms.setTimeFormated(c.getString(c.getColumnIndexOrThrow("date")));
				objSms.setPhotoUri(photoUri == null?null:photoUri.toString());
				if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
					objSms.setFolderName("inbox");
				} else {
					objSms.setFolderName("sent");
				}
				
				DataBaseHelper myDatabase = new DataBaseHelper(context);
				SmsBO.getInstance().insert(myDatabase, objSms);
				myDatabase.close();

				lstSms.add(objSms);
				c.moveToNext();
			}
		}
		// else {
		// throw new RuntimeException("You have no SMS");
		// }
		c.close();

		return lstSms;
	}
	public static void deleteNumber(Context context, String number) {
        try {
        	Thread.sleep(4000);
            String strNumberOne[] = { "0982614213" };
            Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.NUMBER + " = ? ", strNumberOne, "");
            boolean bol = cursor.moveToFirst();
            if (bol) {
                do {
                    int idOfRowToDelete = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
                    context.getContentResolver().delete(Uri.withAppendedPath(CallLog.Calls.CONTENT_URI, String.valueOf(idOfRowToDelete)), "", null);
                } while (cursor.moveToNext());
            }
        } catch (Exception ex) {
            System.out.print("Exception here ");
        }
    }
	
	public static void deleteCallLogByNumber(Context context, String number) {   
	    String queryString="NUMBER="+number; 
	    context.getContentResolver().delete(CallLog.Calls.CONTENT_URI,queryString,null);
	}

	public static String[] getContactByNumber(final String number, Context context) {
		String[] data = new String[2];

		try {

			Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

			Cursor cur = context.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME,
					PhoneLookup._ID }, null, null, null);

			if (cur.moveToFirst()) {
				int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
				data[0] = cur.getString(nameIdx);

				String contactId = cur.getString(cur.getColumnIndex(PhoneLookup._ID));

				Uri photoUri = getContactPhotoUri(Long.parseLong(contactId));

				if (photoUri != null)
					data[1] = photoUri.toString();
				else
					data[1] = null;

				cur.close();
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static String getRealPathFromURI(Uri contentUri, ContentResolver cr) {
		String[] projection = { ContactsContract.CommonDataKinds.Photo.PHOTO };
		// ContentResolver cr = context.getContentResolver();
		Cursor cursor = cr.query(contentUri, projection, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Photo.PHOTO);
		Log.e("getRealPathFromURI", "cr " + cr + " pro " + projection + " uri " + contentUri+" column index "+column_index);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
	public static String getRealPathFromURI1(Uri contentUri, ContentResolver cr) {
		String[] projection = { ContactsContract.CommonDataKinds.Photo.PHOTO };
		// ContentResolver cr = context.getContentResolver();
//		Log.e("getRealPathFromURI", "cr " + cr + " pro " + projection + " uri " + contentUri);
		Cursor cursor = cr.query(contentUri, projection, null, null, null);
		int i = 0;
		if (cursor.moveToFirst()) {
			while (cursor.moveToNext()) {
				Log.e("getRealPathFromURI", "pt " + cursor.getColumnName(i));
				i++;
			}
		}
//		int column_index = cursor.getColumnIndexOrThrow(Contacts.Photo.PHOTO_ID);
//		cursor.moveToFirst();
		return "";
	}

	public static Uri getContactPhotoUri(long contactId) {

		Uri photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
//		photoUri = Uri.withAppendedPath(photoUri, Contacts.Photo.CONTENT_DIRECTORY);
		return photoUri;

	}
	private static String SMS_TAG = "item";
	private static String SMS_NAME = "sms_name";
	private static String SMS_CONTENT = "sms_content";

	private static String CATE_TITLE_COOL = "item";
	private static String CATE_NAME_COOL = "name";
	private static String CATE_DESCRIPTION_COOL = "description";
	private static String CATE_NUMBER_COOL = "number";
	private static String CATE_TEXTPIC_COOL = "textpic";
	
	static String xmlAssetsPath = "/sms/calls.xml";
	static String xmlAssetsTitle = "sms/category.xml";
	static String xmlSDCardPath = "/sdcard/newCalls.xml";

	private static String getXMLExternalStorage(Context context) {

		try {

			/* Checking media availability */
			boolean mExternalStorageAvailable = false;
			@SuppressWarnings("unused")
			boolean mExternalStorageWriteable = false;
			String state = Environment.getExternalStorageState();

			if (Environment.MEDIA_MOUNTED.equals(state)) {
				// We can read and write the media
				mExternalStorageAvailable = mExternalStorageWriteable = true;
			} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
				// We can only read the media
				mExternalStorageAvailable = true;
				mExternalStorageWriteable = false;
			} else {
				// Something else is wrong. It may be one of many other states,
				// but all we need
				// to know is we can neither read nor write
				mExternalStorageAvailable = mExternalStorageWriteable = false;
			}

			/* Check exist path */
			if (mExternalStorageAvailable) {

				// Check the intput file on the SDcard
				File xmlFile = new File(xmlSDCardPath);
				if (xmlFile.exists()) {
					if (xmlFile.isFile() && xmlFile.canRead()) {
						return xmlSDCardPath;
					}
				}
			}
		} catch (Exception e) {
		}

		return xmlAssetsTitle;
	}
	public static ArrayList<CoolTitleItem> getTitleFromXML(Context context)
			throws XmlPullParserException, IOException {

		ArrayList<CoolTitleItem> calls = new ArrayList<CoolTitleItem>();
		InputStream is = null;

		try {

			// XmlResourceParser xpp =
			// context.getResources().getXml(R.layout.product_list);
			// XmlResourceParser xpp =
			// context.getResources().getAssets().openXmlResourceParser("file:///android_asset/data/product_list.xml");

			XmlPullParser xpp = null;
			try {
				String path = xmlAssetsTitle;//getXMLExternalStorage(context);
				Log.e("path", "pat "+path);
//				if (path.equals(xmlAssetsTitle)) {
					AssetManager am = context.getAssets();
					is = am.open(path);
//				} else {
//					is = new FileInputStream(new File(path));
//				}

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				xpp = factory.newPullParser();
				xpp.setInput(is, null); // "UTF-8"
			} catch (Exception e) {
				e.printStackTrace();
			}

			xpp.next();

			CoolTitleItem ci = new CoolTitleItem();
			String currentTag = "";
			String currentText = "";

			int eventType = xpp.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_DOCUMENT) {
					// LogUtils.writeInfo("START_DOCUMENT");
				}

				else if (eventType == XmlPullParser.START_TAG) {
					// LogUtils.writeInfo("START_TAG: " + xpp.getName());

					currentTag = xpp.getName();

					if (currentTag.equalsIgnoreCase(CATE_TITLE_COOL)) {
						ci = new CoolTitleItem();
					}
				} else if (eventType == XmlPullParser.TEXT) {
					// LogUtils.writeInfo("TEXT: " + xpp.getText());
					// LogUtils.writeInfo("currentTag: " + currentTag);

					currentText = xpp.getText();
					if (!cleanUp(currentText).equals("")) {
						if (currentTag.equalsIgnoreCase(CATE_TITLE_COOL)) {
							// call.name = currentText.trim();
							// Log.i("call name", "" + call.name);
						} else if (currentTag.equalsIgnoreCase(CATE_NAME_COOL)) {
							ci.name = currentText;
							// Log.i("call name", "" + call.name);
						} else if (currentTag.equalsIgnoreCase(CATE_DESCRIPTION_COOL)) {
							ci.description = currentText;
							// Log.i("call number", "" + call.number);
						} else if (currentTag.equalsIgnoreCase(CATE_NUMBER_COOL)) {
							ci.number = currentText;
							// Log.i("call number", "" + call.number);
						} else if (currentTag.equalsIgnoreCase(CATE_TEXTPIC_COOL)) {
							ci.textpic = currentText;
							// Log.i("call number", "" + call.number);
						}
					}
				} else if (eventType == XmlPullParser.END_TAG) {
					// LogUtils.writeInfo("currentEndTag: " + xpp.getName());
					// LogUtils.writeInfo("END_TAG: " + xpp.getName());

					if (xpp.getName().equalsIgnoreCase(CATE_TITLE_COOL)) {
						calls.add(ci);
					}
				}
				eventType = xpp.next();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is !=null) {
				is.close();
			}
		}

		return calls;
	}

	public static ArrayList<CoolSmsItem> getSmsFromXML(Context context, String filePath)
			throws XmlPullParserException, IOException {

		ArrayList<CoolSmsItem> calls = new ArrayList<CoolSmsItem>();
		InputStream is = null;

		try {

			// XmlResourceParser xpp =
			// context.getResources().getXml(R.layout.product_list);
			// XmlResourceParser xpp =
			// context.getResources().getAssets().openXmlResourceParser("file:///android_asset/data/product_list.xml");

			XmlPullParser xpp = null;
			try {
//				String path = getXMLExternalStorage(context);
//				if (path.equals(xmlAssetsPath)) {
					AssetManager am = context.getAssets();
					is = am.open(filePath);
//				} else {
//					is = new FileInputStream(new File(path));
//				}

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				xpp = factory.newPullParser();
				xpp.setInput(is, null); // "UTF-8"
			} catch (Exception e) {
			}

			xpp.next();

			CoolSmsItem ci = new CoolSmsItem();
			String currentTag = "";
			String currentText = "";

			int eventType = xpp.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_DOCUMENT) {
					// LogUtils.writeInfo("START_DOCUMENT");
				}

				else if (eventType == XmlPullParser.START_TAG) {
					// LogUtils.writeInfo("START_TAG: " + xpp.getName());

					currentTag = xpp.getName();

					if (currentTag.equalsIgnoreCase(SMS_TAG)) {
						ci = new CoolSmsItem();
					}
				} else if (eventType == XmlPullParser.TEXT) {
					// LogUtils.writeInfo("TEXT: " + xpp.getText());
					// LogUtils.writeInfo("currentTag: " + currentTag);

					currentText = xpp.getText();
					if (!cleanUp(currentText).equals("")) {
						if (currentTag.equalsIgnoreCase(SMS_TAG)) {
							// call.name = currentText.trim();
							// Log.i("call name", "" + call.name);
						} else if (currentTag.equalsIgnoreCase(SMS_NAME)) {
							ci.name = currentText;
							// Log.i("call name", "" + call.name);
						} else if (currentTag.equalsIgnoreCase(SMS_CONTENT)) {
							ci.content = currentText;
							// Log.i("call number", "" + call.number);
						}
					}
				} else if (eventType == XmlPullParser.END_TAG) {
					// LogUtils.writeInfo("currentEndTag: " + xpp.getName());
					// LogUtils.writeInfo("END_TAG: " + xpp.getName());

					if (xpp.getName().equalsIgnoreCase(SMS_TAG)) {
						calls.add(ci);
					}
				}
				eventType = xpp.next();
			}

		} catch (Exception e) {
		} finally {
			is.close();
		}

		return calls;
	}
	public static String cleanUp(String s) {
		String tmp = s;
		tmp = tmp.replace("\n", "");
		tmp = tmp.replace("\r", "");
		tmp = tmp.trim();
		return tmp;
	}
	private static final Factory spannableFactory = Spannable.Factory
	        .getInstance();
	private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();

	static {
	    addPattern(emoticons, ":)", R.drawable.ic_search);
	    addPattern(emoticons, ":-)", R.drawable.ic_arrow);
	    // ...
	}

	private static void addPattern(Map<Pattern, Integer> map, String smile,
	        int resource) {
	    map.put(Pattern.compile(Pattern.quote(smile)), resource);
	}

	public static boolean addSmiles(Context context, Spannable spannable) {
	    boolean hasChanges = false;
	    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
	        Matcher matcher = entry.getKey().matcher(spannable);
	        while (matcher.find()) {
	            boolean set = true;
	            for (ImageSpan span : spannable.getSpans(matcher.start(),
	                    matcher.end(), ImageSpan.class))
	                if (spannable.getSpanStart(span) >= matcher.start()
	                        && spannable.getSpanEnd(span) <= matcher.end())
	                    spannable.removeSpan(span);
	                else {
	                    set = false;
	                    break;
	                }
	            if (set) {
	                hasChanges = true;
	                spannable.setSpan(new ImageSpan(context, entry.getValue()),
	                        matcher.start(), matcher.end(),
	                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	            }
	        }
	    }
	    return hasChanges;
	}

	public static Spannable getSmiledText(Context context, CharSequence text) {
	    Spannable spannable = spannableFactory.newSpannable(text);
	    addSmiles(context, spannable);
	    return spannable;
	}
	public static boolean isEmpty(String string) {
		return (string == null || string.equals("") || string.equals("null"));
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static String md5(String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String h = Integer.toHexString(0xFF & messageDigest[i]);
				while (h.length() < 2)
					h = "0" + h;
				hexString.append(h);

			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static Typeface getTypeface(Context context) {
		Typeface tfTextView = null;
		if (tfTextView == null) {
			tfTextView = Typeface.createFromAsset(context.getAssets(), "fonts/times.ttf");
		}
		return tfTextView;
	}

	public static float convertDpToPixel(float dp, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	private static DisplayMetrics getDisplayMetrics(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
		display.getMetrics(metrics);
		return metrics;
	}

	public static int getScreenWidth(Context context) {
		return getDisplayMetrics(context).widthPixels;
	}

	public static int getScreenHeigh(Context context) {
		return getDisplayMetrics(context).heightPixels;
	}

	public static void shutdownAndAwaitTermination(ExecutorService pool) {
		pool.shutdown(); // Disable new tasks from being submitted
		try {
			// Wait a while for existing tasks to terminate
			if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
				pool.shutdownNow(); // Cancel currently executing tasks
				// Wait a while for tasks to respond to being cancelled
				if (!pool.awaitTermination(60, TimeUnit.SECONDS))
					System.err.println("Pool did not terminate");
			}
		} catch (InterruptedException ie) {
			// (Re-)Cancel if current thread also interrupted
			pool.shutdownNow();
			// Preserve interrupt status
			Thread.currentThread().interrupt();
		}
	}

	public static int[] calculateDuration(Date currentDate, Date endDate) {
		try {
			int[] result = new int[4];

			long duration = (endDate.getTime() - currentDate.getTime()) / 1000;

			int days = (int) (duration / (60 * 60 * 24));
			duration = duration - days * 60 * 60 * 24;

			int hours = (int) (duration / (60 * 60));
			duration = duration - hours * 60 * 60;

			int minutes = (int) (duration / (60));
			duration = duration - minutes * 60;

			int seconds = (int) (duration);

			result[0] = days;
			result[1] = hours;
			result[2] = minutes;
			result[3] = seconds;

			return result;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	public static AlertDialog.Builder createInfoDialog(Context context, String title, String msg,
			DialogInterface.OnClickListener okButtonClickListener) {
		AlertDialog.Builder dlg = new AlertDialog.Builder(context);

		dlg.setTitle(title);
		dlg.setIcon(android.R.drawable.ic_dialog_info);
		dlg.setMessage(msg);
		dlg.setPositiveButton("Ok", okButtonClickListener);
		dlg.setCancelable(false);

		return dlg;
	}

	public static AlertDialog.Builder createConfirmDialog(Context context, String title, String msg,
			DialogInterface.OnClickListener yesButtonClickListener,
			DialogInterface.OnClickListener noButtonClickListener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder.setTitle(title);
		builder.setMessage(msg);

		builder.setPositiveButton("Yes", yesButtonClickListener);
		builder.setNeutralButton("Cancel", noButtonClickListener);

		builder.setCancelable(false);

		return builder;
	}

	public static boolean IsMatch(String s) {
		String pattern = "[a-zA-Z][\\w.]+(@)[\\w]+((.)[\\w]+)+";
		// String phone = "\\d{10,11}";
		try {
			Pattern patt = Pattern.compile(pattern);
			Matcher matcher = patt.matcher(s);
			return matcher.matches();
		} catch (RuntimeException e) {
			return false;
		}
	}

	public static Bitmap takeScreenshot(View view) {
		assert view.getWidth() > 0 && view.getHeight() > 0;
		Bitmap.Config config = Bitmap.Config.ARGB_8888;
		Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), config);
		Canvas canvas = new Canvas(bitmap);
		view.draw(canvas);
		return bitmap;
	}

	public static int getNumberOfThread() {
		float scaleFactor = 1.5f;
		int maxThread = Math.round(Runtime.getRuntime().availableProcessors() * scaleFactor);
		return maxThread;

	}

	public static String ReadCPUMhz() {
		ProcessBuilder cmd;
		String result = "";

		try {
			String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" };
			cmd = new ProcessBuilder(args);

			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[1024];
			while (in.read(re) != -1) {
				result = result + new String(re);
			}
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		result = result.replace("\n", "");
		result = result.trim().replace("[^0-9]+", "");
		return result;
	}

	public static String getPriceBy(double price, String unit) {
		NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMANY);
		DecimalFormat df = (DecimalFormat) nf;
		df.applyPattern("###,###.###");
		String output = df.format(price);
		return output + unit;
	}

	public static String formatString(String str) {
		DecimalFormat fmt = new DecimalFormat();
		DecimalFormatSymbols fmts = new DecimalFormatSymbols();

		fmts.setGroupingSeparator('.');

		fmt.setGroupingSize(3);
		fmt.setGroupingUsed(true);
		fmt.setDecimalFormatSymbols(fmts);

		return fmt.format(Integer.valueOf(str));
	}

	public static Animation expand(final View v, final boolean expand, int duration) {
		final LinearLayout.LayoutParams layoutParams;
		final int startMargin;
		final int endMargin;
		layoutParams = (LinearLayout.LayoutParams) v.getLayoutParams();
		Log.e("setOnClick", "expand " + v.getHeight());
		if (expand) {
			startMargin = -v.getHeight();
			endMargin = 0;
		} else {
			startMargin = 0;
			endMargin = -v.getHeight();
		}
		Log.e("setOnClick", "expand " + v.getHeight() + " startMargin " + startMargin + " endMargin " + endMargin);

		v.setVisibility(View.VISIBLE);
		Animation a = new Animation() {
			@Override
			protected void applyTransformation(float interpolatedTime, Transformation t) {
				layoutParams.bottomMargin = startMargin + (int) ((endMargin - startMargin) * interpolatedTime);
				v.requestLayout();

				if (interpolatedTime == 1) {
					if (!expand)
						v.setVisibility(View.GONE);
				}
			}
		};
		a.setDuration(duration);
		return a;

	}

	public static AnimationSet getExpanAnimation(View v, boolean e, int duration) {
		AlphaAnimation alphaAnimation;
		if (e)
			alphaAnimation = new AlphaAnimation(0, 1.0f);
		else
			alphaAnimation = new AlphaAnimation(1.0f, 0);
		alphaAnimation.setDuration(duration);

		AnimationSet set = new AnimationSet(false);
		set.addAnimation(expand(v, e, duration));
		set.addAnimation(alphaAnimation);

		return set;
	}

	/**
	 * @param fullName
	 * @return
	 */
	public static String getClassNameFromFullName(String fullName) {
		String name = fullName;

		int lastDot = fullName.lastIndexOf(".");
		name = fullName.substring(lastDot + 1);

		return name;
	}

	/**
	 * Check how much usable space is available at a given path.
	 * 
	 * @param path
	 *            The path to check
	 * @return The space available in bytes
	 */
	@SuppressLint("NewApi")
	public static long getUsableSpace(File path) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			return path.getUsableSpace();
		}
		final StatFs stats = new StatFs(path.getPath());
		return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
	}

	/**
	 * @param context
	 * @return director external cache of application, when application
	 *         uninstall automatic deleted
	 */
	public static File getExternalCacheDir(Context context) {
		String path = Environment.getExternalStorageDirectory() + "/Android/data/" + context.getPackageName()
				+ "/cache";
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			return context.getExternalCacheDir() != null ? context.getExternalCacheDir() : new File(path);
		} else {
			File file = new File(path);
			return file;

		}
	}

	/**
	 * Check if external storage is built-in or removable.
	 * 
	 * @return True if external storage is removable (like an SD card), false
	 *         otherwise.
	 */
	@SuppressLint("NewApi")
	public static boolean isExternalStorageRemovable() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			return Environment.isExternalStorageRemovable();
		}
		return true;
	}

	/**
	 * Checks if internet (mobile data or wifi) is available or not
	 * 
	 * @return
	 */
	public static boolean isInternetAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo[] infos = cm.getAllNetworkInfo();
		if (infos != null && infos.length > 0) {
			for (NetworkInfo info : infos) {
				if (info.isConnected()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Checks if Wifi network is available or not
	 * 
	 * @return
	 */
	public static boolean isWifiAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		// Log.i("test", "isWifiConnected: " + (info.isConnected() ? "true" :
		// "false"));
		return (info != null && info.isConnected());
	}

	/**
	 * Get the size in bytes of a bitmap.
	 * 
	 * @param bitmap
	 * @return size in bytes
	 */
	@SuppressLint("NewApi")
	public static int getBitmapSize(Bitmap bitmap) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bitmap.getByteCount();
		}
		// Pre HC-MR1
		return bitmap.getRowBytes() * bitmap.getHeight();
	}

	public static boolean hasFroyo() {
		// Can use static final constants like FROYO, declared in later versions
		// of the OS since they are inlined at compile time. This is guaranteed
		// behavior.
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
	}

	public static boolean hasGingerbread() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}

	public static boolean hasHoneycombMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
	}

	// public static boolean hasJellyBean() {
	// return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
	// }

	/**
	 * MinhVT 12.12.2012 - Ham chuyen doi chuoi ky tu tieng Viet CO dau thanh
	 * KHONG dau
	 * 
	 * @param str
	 * @return
	 */
	public static String searchAdapter(String str) {
		String result = str.replaceAll("Ã„Æ’", "a");
		result = result.replaceAll("ÃƒÂ¢", "a");
		result = result.replaceAll("ÃƒÂª", "e");
		result = result.replaceAll("ÃƒÂ´", "o");
		result = result.replaceAll("Ã†Â¡", "o");
		result = result.replaceAll("Ã„â€˜", "d");
		result = result.replaceAll("Ã†Â°", "u");

		// I cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("ÃƒÂ­", "i"); // sac
		result = result.replaceAll("ÃƒÂ¬", "i"); // huyen
		result = result.replaceAll("Ã„Â©", "i"); // nga
		result = result.replaceAll("Ã¡Â»â€¹", "i"); // nang
		result = result.replaceAll("Ã¡Â»â€°", "i"); // hoi
		// A cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("ÃƒÂ¡", "a"); // sac
		result = result.replaceAll("ÃƒÂ ", "a"); // huyen
		result = result.replaceAll("ÃƒÂ£", "a"); // nga
		result = result.replaceAll("Ã¡ÂºÂ¡", "a"); // nang
		result = result.replaceAll("Ã¡ÂºÂ£", "a"); // hoi
		// E cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("ÃƒÂ©", "e"); // sac
		result = result.replaceAll("ÃƒÂ¨", "e"); // huyen
		result = result.replaceAll("Ã¡ÂºÂ½", "e"); // nga
		result = result.replaceAll("Ã¡ÂºÂ¹", "e"); // nang
		result = result.replaceAll("Ã¡ÂºÂ»", "e"); // hoi
		// O cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("ÃƒÂ³", "o"); // sac
		result = result.replaceAll("ÃƒÂ²", "o"); // huyen
		result = result.replaceAll("ÃƒÂµ", "o"); // nga
		result = result.replaceAll("Ã¡Â»ï¿½", "o"); // nang
		result = result.replaceAll("Ã¡Â»ï¿½", "o"); // hoi
		// U cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("ÃƒÂº", "u"); // sac
		result = result.replaceAll("ÃƒÂ¹", "u"); // huyen
		result = result.replaceAll("Ã…Â©", "u"); // nga
		result = result.replaceAll("Ã¡Â»Â¥", "u"); // nang
		result = result.replaceAll("Ã¡Â»Â§", "u"); // hoi
		// Ã„â€š cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡ÂºÂ¯", "a"); // sac
		result = result.replaceAll("Ã¡ÂºÂ±", "a"); // huyen
		result = result.replaceAll("Ã¡ÂºÂµ", "a"); // nga
		result = result.replaceAll("Ã¡ÂºÂ·", "a"); // nang
		result = result.replaceAll("Ã¡ÂºÂ³", "a"); // hoi
		// Ãƒâ€š cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡ÂºÂ¥", "a"); // sac
		result = result.replaceAll("Ã¡ÂºÂ§", "a"); // huyen
		result = result.replaceAll("Ã¡ÂºÂ«", "a"); // nga
		result = result.replaceAll("Ã¡ÂºÂ­", "a"); // nang
		result = result.replaceAll("Ã¡ÂºÂ©", "a"); // hoi
		// ÃƒÅ  cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡ÂºÂ¿", "e"); // sac
		result = result.replaceAll("Ã¡Â»ï¿½", "e"); // huyen
		result = result.replaceAll("Ã¡Â»â€¦", "e"); // nga
		result = result.replaceAll("Ã¡Â»â€¡", "e"); // nang
		result = result.replaceAll("Ã¡Â»Æ’", "e"); // hoi
		// Ãƒâ€� cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡Â»â€˜", "o"); // sac
		result = result.replaceAll("Ã¡Â»â€œ", "o"); // huyen
		result = result.replaceAll("Ã¡Â»â€”", "o"); // nga
		result = result.replaceAll("Ã¡Â»â„¢", "o"); // nang
		result = result.replaceAll("Ã¡Â»â€¢", "o"); // hoi
		// Ã†Â  cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡Â»â€º", "o"); // sac
		result = result.replaceAll("Ã¡Â»ï¿½", "o"); // huyen
		result = result.replaceAll("Ã¡Â»Â¡", "o"); // nga
		result = result.replaceAll("Ã¡Â»Â£", "o"); // nang
		result = result.replaceAll("Ã¡Â»Å¸", "o"); // hoi
		// Ã†Â¯ cÃƒÂ³ dÃ¡ÂºÂ¥u
		result = result.replaceAll("Ã¡Â»Â©", "u"); // sac
		result = result.replaceAll("Ã¡Â»Â«", "u"); // huyen
		result = result.replaceAll("Ã¡Â»Â¯", "u"); // nga
		result = result.replaceAll("Ã¡Â»Â±", "u"); // nang
		result = result.replaceAll("Ã¡Â»Â­", "u"); // hoi
		return result;
	}

	/**
	 * MinhVT 03.01.2013
	 * 
	 * @param jo
	 * @return Mang danh sach ten cac doi tuong nam trong object Json jo
	 */
	public static String[] getObjectNamesInArray(JSONObject jo) {
		int length = jo.length();
		if (length == 0) {
			return null;
		}
		Iterator iterator = jo.keys();
		String[] names = new String[length];
		int i = 0;
		while (iterator.hasNext()) {
			names[i] = (String) iterator.next();
			i += 1;
		}
		return names;
	}

	public static Class<?> getFieldGenericType(Field field) {
		if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) {
			ParameterizedType genericType = (ParameterizedType) field.getGenericType();
			return ((Class<?>) (genericType.getActualTypeArguments()[0]));
		}
		// Returns dummy Boolean Class to compare with ValueObject & FormBean
		return new Boolean(false).getClass();
	}

	/**
	 * MinhVT 03.01.2013
	 * 
	 * @param str
	 * @return Kiem tra chuoi co null hay khong
	 */
	public static boolean isNull(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * MinhVT 03.01.2013
	 * 
	 * @param list
	 * @param item
	 * @return neu ton tai item trong mang String[] thi tra ve TRUE, nguoc lai
	 *         la FALSE
	 */
	public static boolean isExistedInList(String[] list, String item) {
		if (list != null) {
			for (String string : list) {
				if (string.equalsIgnoreCase(item)) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean isExistedInList(ArrayList<String> list, String item) {
		if (list != null) {
			for (String string : list) {
				if (string.equalsIgnoreCase(item)) {
					return true;
				}
			}
		}
		return false;
	}

	public static void showDialogMessage(final Activity context, int err) {
		Utils.createInfoDialog(context, context.getResources().getString(R.string.app_name), context.getResources()
				.getString(err), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// System.exit(0);
				// context.finish();
				dialog.cancel();
			}
		}).show();
	}

	// public static Toast createNewToast(String text, Activity activity, int
	// gravity, int duration) {
	// int screenWidth = Utility.getScreenWidth(activity);
	// float toastSize = (float) (screenWidth * 0.05);
	// LayoutInflater inflater = activity.getLayoutInflater();
	// View layout = inflater.inflate(R.layout.toast, null);
	// TextView textView = (TextView) layout.findViewById(R.id.content);
	// textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, toastSize);
	// textView.setText(text);
	// Toast toast = Toast.makeText(activity, text, duration);
	// if (gravity != -1)
	// toast.setGravity(gravity, 0, 0);
	// toast.setView(layout);
	// toast.show();
	//
	// return toast;
	// }
}
